<template>
  <!-- K线 -->
  <Candlestick :coinInfo="coinInfo" type="secondContract"></Candlestick>
  <!-- 1:1还原UI区域 -->
  <div class="order-ui-box">
    <div class="order-ui-label">{{ _t18('select_cycle') }}</div>
    <div class="order-ui-row order-ui-row-top">
      <div class="order-ui-select-wrap" @click="openTimePopup">
        <img class="order-ui-icon-time" src="@/assets/defi/time.png" alt="time" />
        <span class="order-ui-select-text">{{ cycleObj.period }}</span>
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style="margin-left:4px;"><path d="M4 6l4 4 4-4" stroke="#888" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </div>
      <button class="order-ui-btn order-ui-btn-up" :class="{active: selectedDirection===1}" @click="selectDirection(1)">{{ _t18('option_buy_up') }}</button>
      <button class="order-ui-btn order-ui-btn-down" :class="{active: selectedDirection===0}" @click="selectDirection(0)">{{ _t18('option_buy_short') }}</button>
    </div>
    <div class="order-ui-row order-ui-row-rate">
      <div class="order-ui-rate-box">
        <span class="order-ui-rate-label" v-if="selectedDirection===1">{{ _t18('option_buy_up') }}</span>
        <span class="order-ui-rate-label" v-if="selectedDirection===0">{{ _t18('option_buy_short') }}</span>
        <span class="order-ui-rate-value">{{ cycleObj.odds }} %</span>
      </div>
    </div>
    <div class="order-ui-row order-ui-row-bg">
      <div class="order-ui-row order-ui-row-amount">
        <span class="order-ui-amount-label">{{ _t18('pledge_purchasing_price') }}</span>
        <span class="order-ui-amount-balance">{{ _t18('pledge_Available_Balance') }}：{{ availableBalance }} USDT</span>
      </div>
      <div class="order-ui-row order-ui-row-input">
        <div class="order-ui-currency">
          <img class="order-ui-icon-usd" src="/static/no-rename/usd.png" alt="usd" />
          <span>USD</span>
        </div>
        <input class="order-ui-input" placeholder=">=100USD" v-model="amount" type="number" min="100"
          @input="if($event.target.value<0)$event.target.value=amount=''; else amount=$event.target.value.replace(/[^\d.]/g,'')" 
        />
        <button class="order-ui-btn-all">{{ _t18('all') }}</button>
      </div>
    </div>
    <div class="order-ui-row order-ui-row-profit">
      <span class="order-ui-profit-label">{{ _t18('income') }}：</span>
      <span class="order-ui-profit-value">{{ cycleObj.odds * amount / 100 }}</span>
    </div>

    <div style="height: 150px;"></div>
  </div>
  <!-- 时间选择弹窗 -->
  <div v-if="showTimePopup" class="time-popup-mask" @click.self="closeTimePopup">
    <div class="time-popup-sheet">
      <div class="time-popup-close" @click="closeTimePopup">✕</div>
      <div class="time-popup-list">
        <div v-for="(item, index) in cycleList" 
        :key="index" class="time-popup-item" 
        :class="{active: cycleIndex === index}" 
        @click="selectTime(index, item)">
          {{ item.period }}
        </div>
      </div>
    </div>
  </div>
  <!-- 底部确认下单按钮 -->
  <div class="order-bottom-bar">
    <button class="order-confirm-btn"  @click="handleOrderBtn">{{ _t18('12_xiadan') }}</button>
  </div>
  <!-- <div class="line"></div> -->
  <!-- 订单信息 -->
   <!-- Toast -->
  <div v-if="showToast" class="toast">{{ toastMsg }}</div>
  <!-- 订单进度弹窗 -->
  <div v-if="showOrderProgress" class="order-progress-modal" @click.self="closeOrderProgress">
    <div class="order-progress-content">
      <img src="/static/img/WAB_b2d79c23_u2o.b1482901.svg" class="order-progress-icon" />
      <div class="order-progress-title">Chat GPT正在運行...</div>
      <div class="order-progress-desc">
        <div v-if="currentTyped">{{ currentTyped }}</div>
      </div>
      <div class="order-progress-bar-wrap">
        <div class="order-progress-bar-bg">
          <div class="order-progress-bar" :style="{width: progress+'%'}"></div>
        </div>
        <div class="order-progress-percent" :style="{left: `calc(${progress}% - 30px)`}">{{ progress.toFixed(2) }}%</div>
      </div>
    </div>
  </div>
  <!-- 简单确认弹窗 -->
  <div v-if="showSimpleConfirm" class="simple-confirm-mask" @click.self="closeSimpleConfirm">
    <div class="simple-confirm-modal">
      <div class="simple-confirm-title">確認下單？</div>
      <div class="simple-confirm-btns">
        <button class="simple-cancel" @click="closeSimpleConfirm">取消</button>
        <button class="simple-ok" @click="handleSimpleConfirm">確認</button>
      </div>
    </div>
  </div>
  <!-- 确认下单模态窗 -->
  <div v-if="showConfirmModal && 1==0" class="confirm-modal-mask" @click.self="closeConfirmModal">
    <div class="confirm-modal">
      <div class="confirm-modal-header">
        <span>訂單資訊</span>
        <span class="confirm-modal-close" @click="closeConfirmModal">×</span>
      </div>
      <div class="confirm-modal-timer">
        <span class="timer-box red">{{ String(Math.floor(countDown/3600)).padStart(2, '0') }}</span>
        <span class="timer-box green">{{ String(Math.floor((countDown % 3600) / 60)).padStart(2, '0') }}</span>
        <span class="timer-box yellow">{{ String(countDown % 60).padStart(2, '0') }}</span>
      </div>
      <div class="confirm-modal-info">
        <div class="row"><span class="label">方向</span><span v-if="selectedDirection==1" class="value green">漲</span><span v-if="selectedDirection==0" class="value red">跌</span></div>
        <div class="row"><span class="label">金額</span><span class="value">{{ amount }}U</span></div>
        <div class="row"><span class="label">购买價格</span><span class="value">{{ buyPrice }}</span></div>
        <div class="row"><span class="label">当前價格</span><span class="value">{{ coinPriceInfo?.close }}</span></div>
        <div class="row"><span class="label">獲利</span><span class="value">
          <svg data-v-fbb24b0a="" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="20px" height="26px" viewBox="0 0 24 30" xml:space="preserve"><rect data-v-fbb24b0a="" x="0" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0s" dur="0.6s" repeatCount="indefinite"></animate></rect><rect data-v-fbb24b0a="" x="8" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate></rect><rect data-v-fbb24b0a="" x="16" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate></rect></svg>
           </span></div>
      </div>
      <div class="confirm-modal-btns">
        <button class="view-btn" @click="handleViewOrder">查看訂單</button>
        <button class="continue-btn" @click="handleContinueOrder">繼續下單</button>
      </div>
    </div>
  </div>
  <SlideUpPopup v-model="showConfirmModal">
      <!-- <div class="confirm-modal"> -->
      <div class="confirm-modal-header">
        <div>{{ coinInfo.symbol }}</div>
        <!-- <span class="confirm-modal-close" @click="closeConfirmModal">×</span> -->
         <span class="confirm-modal-close" @click="closeConfirmModal">{{ coinPriceInfo?.close }}</span>
      </div>
      <div class="circle" style="text-align: center;">
          <van-circle
            v-model:current-rate="currentRate"
            :rate="(1 - countDown / Number(cycleObj.period)) * 100"
            :speed="100"
            :stroke-width="`100`"
            :size="`100px`"
            :layer-color="`#D9D9D9`"
            :color="`#3c5fe7`"
            
          >
            <!-- 插槽内容，自定义文字 -->
            <div class="circle-text" style="font-weight: bold;font-size: 16px;">{{ countDown }}S</div>
          </van-circle>
        </div>
      <div class="confirm-modal-info">
        <div class="row">
          <span class="label">方向</span>
          <span v-if="selectedDirection==1" class="value green">看漲 |> 0.01%</span>
          <span v-if="selectedDirection==0" class="value red">看跌 |> 0.01%</span>
        </div>
        <div class="row"><span class="label">金額</span><span class="value">{{ amount }}U</span></div>
        <div class="row"><span class="label">购买價格</span><span class="value">{{ buyPrice }}</span></div>
        <div class="row"><span class="label">獲利率</span><span class="value">{{ orderRate }}</span></div>
        <!-- <div class="row"><span class="label">当前價格</span><span class="value">{{ coinPriceInfo?.close }}</span></div> -->
        <div class="row"><span class="label">獲利</span><span class="value">
          <svg data-v-fbb24b0a="" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="20px" height="26px" viewBox="0 0 24 30" xml:space="preserve"><rect data-v-fbb24b0a="" x="0" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0s" dur="0.6s" repeatCount="indefinite"></animate></rect><rect data-v-fbb24b0a="" x="8" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate></rect><rect data-v-fbb24b0a="" x="16" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate></rect></svg>
           </span></div>
      </div>
      <div class="confirm-modal-btns">
        <button class="order-confirm-btn" @click="handleContinueOrder">繼續下單</button>
      </div>
    <!-- </div> -->
  </SlideUpPopup>
  <SlideUpPopup v-model="showOver">
      <!-- <div class="confirm-modal"> -->
      <div class="confirm-modal-header">
        <div>{{ coinInfo.symbol }}</div>
        <!-- <span class="confirm-modal-close" @click="closeConfirmModal">×</span> -->
         <!-- <span class="confirm-modal-close" @click="closeConfirmModal">{{ coinPriceInfo?.close }}</span> -->
      </div>
      <div class="green" style="text-align: center;font-size: 20px;margin: 20px;color:#1ecb81" v-if="orderObj?.rewardAmount > 0">
          +{{ orderObj?.rewardAmount }}
      </div>
      <div class="red" style="text-align: center;font-size: 20px;margin: 20px;color: #ff5a5a;" v-if="orderObj?.rewardAmount == 0">
          -{{ orderObj?.betAmount }}
      </div>
      <div class="confirm-modal-info">
        <div class="row">
          <span class="label">方向</span>
          <span v-if="orderObj?.betContent==1" class="value green">看漲 |> 0.01%</span>
          <span v-if="orderObj?.betContent==0" class="value red">看跌 |> 0.01%</span>
        </div>
        <div class="row"><span class="label">金額</span><span class="value">{{ orderObj?.betAmount }}U</span></div>
        <div class="row"><span class="label">购买價格</span><span class="value">{{ orderObj?.openPrice }}</span></div>
        <div class="row"><span class="label">獲利率</span><span class="value">{{ orderObj?.rate * 100 }}%</span></div>
        <!-- <div class="row"><span class="label">当前價格</span><span class="value">{{ coinPriceInfo?.close }}</span></div> -->
        <div class="row"><span class="label">獲利</span><span class="value">
          <svg data-v-fbb24b0a="" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="20px" height="26px" viewBox="0 0 24 30" xml:space="preserve"><rect data-v-fbb24b0a="" x="0" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0s" dur="0.6s" repeatCount="indefinite"></animate></rect><rect data-v-fbb24b0a="" x="8" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite"></animate></rect><rect data-v-fbb24b0a="" x="16" y="10" width="4" height="10" fill="var(--text-color)" opacity="0.2"><animate data-v-fbb24b0a="" attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate><animate data-v-fbb24b0a="" attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite"></animate></rect></svg>
           </span></div>
      </div>
      <div class="confirm-modal-btns">
        <button class="order-confirm-btn" @click="countdownClose">繼續下單</button>
      </div>
    <!-- </div> -->
  </SlideUpPopup>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { _div } from '@/utils/decimal'
import { 
  countdownNum, 
  matchText, 
  formatExpectedProfit, 
  formatCurrentcurrency,
  formatExpectedProfitColor,
  profitAndloss,
  profitAndlossColor 
} from '@/utils/filters'
import { showLoadingToast, closeToast } from 'vant'
import { useRoute } from 'vue-router'
import Candlestick from '../../common/candlestick.vue'
import ContractHistory from './contractHistory.vue'
import ShareCommissionDetail from './../../common/ShareCommissionDetail.vue'
import OverlayPulic from '@/components/Popup/overlayPulic.vue'
import { secondContractOrderselectOrderList } from '@/api/trade/index'
// import { formatCurrentcurrency, profitAndloss } from '@/utils/filters'
import { getPeriodList, createSecondContractOrder } from '@/api/trade/index'
import { _t18 } from '@/utils/public'
import { useUserStore } from '@/store/user'
import SlideUpPopup from './SlideUpPopup.vue'

import { socketDict } from '@/config/dict'
import PubSub from 'pubsub-js'
import { useTradeStore } from '@/store/trade/index'
import { useI18n } from 'vue-i18n'
import { useToast } from '@/hook/useToast'
const { _toast } = useToast()
const { t } = useI18n()
const router = useRouter()
const tradeStore = useTradeStore()
const props = defineProps({
  coinInfo: {
    type: Object,
    default: () => {}
  }
})
// 倒计时
const currentRate = ref(0)
const $route = useRoute()
const currentEntruset = ref(0) // 委托状态 0 进行中 1 完成
const currentEye = ref(true) // 当前眼睛
const historyList = ref([])
const historyNewList = ref([])
// 当前委托/历史委托切换
const switchingEntrust = (e) => {
  currentEntruset.value = e
  historyNewList.value = []
  getList(e)
}
// 切换眼睛（隐藏其他交易数据）
const switchingEye = () => {
  currentEye.value = !currentEye.value
  filterEyes()
}
/** 过滤当前的数据 */
const filterEyes = () => {
  if (currentEye.value) {
    historyNewList.value = historyList.value
  } else {
    historyNewList.value = formatCurrentcurrency(historyList.value, props.coinInfo.symbol)
  }
}
console.log(props.coinInfo)
console.log(props.coinInfo.symbol)
// 刷新
const toRefresh = () => {
  showLoadingToast({
    forbidClick: true,
    duration: 0
  })
  updateList()
}

const updateList = () => {
  historyNewList.value = []
  getList(currentEntruset.value)
}

defineExpose({
  updateList
})
watch(
  () => $route.query,
  () => {
    filterEyes()
  }
)
watch(
  () => currentEye.value,
  (n) => {
    if (n) {
      historyNewList.value = historyList.value
    }
  }
)
/**过滤倒计时 */
const fifterTimeDown = (data) => {
  if (data.length > 0) {
    if (!currentEntruset.value) {
      data.forEach((element, i) => {
        if (element.time <= 0) {
          data.splice(i, 1)
        }
      })
    }
    return data
  } else {
    return data
  }
}
const remove = (item, num) => {
  if (num < 0) {
    historyNewList.value.forEach((element, index) => {
      if (element.userId === item.userId) {
        historyNewList.value.splice(index, 1)
      }
    })
  }
}
// 完成更新
const updateRecord = () => {
  getNumber(0)
  getNumber(1)
  getList(currentEntruset.value)
}

const userStore = useUserStore()
// 用户余额信息
const { asset } = storeToRefs(userStore)

const availableBalance = ref('') //  可用余额
// console.log(asset.value.find(item => item.symbol == 'usdt' && item.type == 3))
availableBalance.value = asset.value.find(item => item.symbol == 'usdt' && item.type == 3).amout + ''
    // asset.value.filter((item) => {
    //   return item.symbol === 'usdt'
    // })[0].availableAmount + ''

// 获取委托
const firstNum = ref(0)
const secondNum = ref(0)
const getList = async (status) => {
  try {
    const res = await secondContractOrderselectOrderList({ status: status, aiType: '1' })
    if (res.code === 200) {
      const result = res.data
      if (status) {
        secondNum.value = result.length
      } else {
        firstNum.value = result.length
      }
      historyList.value = fifterTimeDown(result)
      historyNewList.value = historyList.value
      filterEyes()
      closeToast()
    } else {
      closeToast()
    }
  } catch (error) {
    closeToast()
  }
}
const getNumber = async (status) => {
  try {
    const res = await secondContractOrderselectOrderList({ status: status })
    if (res.code === 200) {
      const result = res.data
      if (status) {
        secondNum.value = result.length
      } else {
        firstNum.value = result.length
      }
    }
  } catch (error) {}
}

// 时间选择弹窗相关
const showTimePopup = ref(false)
const timeOptions = [
  { label: '60s', value: '60s' },
  { label: '3min', value: '3min' },
  { label: '5min', value: '5min' },
  { label: '15min', value: '15min' },
  { label: '30min', value: '30min' },
  { label: '1hour', value: '1hour' },
]
const selectedTime = ref(timeOptions[0].value)

const amount = ref('') // 购买金额输入
const showOrderProgress = ref(false) // 控制底部弹窗
const progress = ref(0) // 进度条百分比
const progressTimer = ref(null)
const toastMsg = ref('')
const showToast = ref(false)

const cycleObj = ref({})
const cycleList = ref([]) // 周期列表
// import { watch } from 'fs'
const isCloseCountdown = ref(false) // 根据关闭按钮展示是否开始倒计时

const cycleIndex = ref('60s')
const openTimePopup = () => { showTimePopup.value = true }
const closeTimePopup = () => { showTimePopup.value = false }
// const selectTime = (item) => {
//   selectedTime.value = item.value
//   closeTimePopup()
// }
function selectTime(index, item) {
  cycleIndex.value = index
  // showTimePopup.value = false
  cycleObj.value = item
  closeTimePopup()
}


/** 获取周期 */
const getCycleList = async (id) => {
  try {
    const res = await getPeriodList({ secondId: id })
    if (res.code === 200) {
      console.log(res.data)
      if (!res.data || res.data.length === 0) {
        const res1 = await getPeriodList({ secondId: 42 })
        if (res1.code === 200) {
          
            cycleList.value = res1.data
            cycleObj.value = cycleList.value[0]
          
          
        }
      } else {
        cycleList.value = res.data
        cycleObj.value = cycleList.value[0]
      }
      
    }
  } catch (error) {}
}
getCycleList(props.coinInfo.id)
onMounted(() => {
  getList(0)
  getNumber(1)
  
  
})

// 分享收益
const shareShow = ref(false)
const revenueDetails = ref({}) // 收益详情
const closePosition = _t18('Close_position')

// 盈亏金额计算

const shareRevenue = (model) => {
  // 盈亏金额
  let amuout = profitAndloss(model.betAmount, model.rewardAmount)

  // 二维码链接
  const shareLink = `${location.origin}/#/i&`
  const userStore = useUserStore()
  const userInfo = userStore.userInfo
  const sharkCode = userInfo?.user?.activeCode

  // 组件赋值
  revenueDetails.value = {
    profitAndLossAmount: amuout > 0 ? amuout.toString() : amuout, // 盈亏金额
    TransactionType: model.coinSymbol.toUpperCase() + '/' + model.baseSymbol.toUpperCase(), // 交易类型
    CurrencyName: closePosition, // 币种名
    OpeningPrice: model.openPrice.toString(), // 开仓价格
    ClosingPrice: model.closePrice.toString(), // 平仓价格
    type: model.type,
    // QrCode: shareLink + sharkCode, // 二维码
    QrCode: location.origin,
    bgType: `1`, //背景类型，此参数当为用户设置， 暂定1 为默认白色
    currencyUnit: model.baseSymbol.toUpperCase()
  }
  console.log(revenueDetails)
  shareShow.value = !shareShow.value
}

/**
 * 订单结算，更新订单和用户信息
 */
// const userStore = useUserStore()
const settlementKey = ref('')

const settlementNotification = () => {
  /**
   * 结算改变通知
   */
  settlementKey.value = PubSub.subscribe(socketDict.SETTLEMENT, (key, data) => {
    const { type } = JSON.parse(data.date.message)
    if (type == 3) {
      console.log(888)
      getList(0)
      getList(1)
      userStore.getUserInfo()
    }
  })
}
settlementNotification()
onUnmounted(() => {
  settlementKey && PubSub.unsubscribe(settlementKey)
})
const submit = () => {
  if (DIFF_ISFREEZE.includes(__config._APP_ENV)) {
    if (_isFreeze(DIFF_ISFREEZE)) {
      submitForm()
    }
  } else {
    submitForm()
  }
}

/**
 * 币种价格详情
 */
const coinPriceInfo = computed(() => tradeStore.allCoinPriceInfo[props.coinInfo.coin])

// 确定
const buyPrice = ref(0)
const orderRate = ref(0)
// 订单id用于查询倒计时订单
const orderId = ref('')

const determine = async () => {
  // showConfirmModal.value = true
  // countDown.value = 60
  // return 0
  // if (Number(amount.value) < cycleObj.value.minAmount) {
  //   // 最少输入
  //   return showToast(`${_showName(`minimum_input`)} ${cycleObj.value.minAmount} USDT`)
  // }
  // if (Number(amount.value) > cycleObj.value.maxAmount) {
  //   // 最多输入
  //   return showToast(`${_showName(`Maximum_input`)} ${cycleObj.value.maxAmount} USDT`)
  // }
  if (Number(amount.value) > Number(availableBalance.value)) {
    // 输入量超出可用余额
    return _toast('Input_amount_exceeds')
  }
  // if (riseFall.value == 'rise') {

  // }
  let data = {
    betContent: selectedDirection.value,
    betAmount: amount.value,
    openPrice: coinPriceInfo.close,
    openTime: new Date().getTime(),
    symbol: props.coinInfo.symbol,
    coinSymbol: props.coinInfo.coin,
    baseSymbol: 'usdt',
    periodId: cycleObj.value.id,
    aiType: '1',
    // buyPlat: buyExchange.value.id,
    // sellPlat: sellExchange.value.id
  }
  try {
    const res = await createSecondContractOrder(data)
    if (res.code === 200) {
      orderId.value = res.data.id
      // handelClose()
      closeSimpleConfirm()
      // openConfirmModal()
      setTimeout(() => {
        showConfirmModal.value = true
        buyPrice.value = res.data.openPrice
        orderRate.value = res.data.rate
        countDown.value = Number(cycleObj.value.period)
        overFlag.value = true
        isCloseCountdown.value = true
      }, 1000)
    } else {
      showToast(res.msg)
    }
  } catch (error) {}
}

const countDown = ref(0) // 初始倒计时
const overFlag = ref(false)
// import { secondContractOrderselectOrderList } from '@/api/trade/index'

// 订单数据
const orderObj = ref(null)
const timer = ref(null)


watch(() => isCloseCountdown.value, (val) => {
  if (val) {
    startCountdown()
  } else {
    stopCountdown()
  }
})

function startCountdown() {
  stopCountdown() // 避免重复
  timer.value = setInterval(() => {
    if (countDown.value > 0) {
      countDown.value--
      if (countDown.value === 1) {
        // 调用订单接口
        const data = { status: 1, id: orderId.value }
        secondContractOrderselectOrderList(data).then((res) => {
          if (res.code === 200) {
            orderObj.value = res.data[0]
          } else {
            showToast(res.msg)
          }
        })
      }
    } else {
      console.log(countDown)
      stopCountdown()
      showConfirmModal.value = false
      userStore.getUserInfo()
      if (overFlag.value) {
        showOver.value = true
      }
    }
  }, 1000)
}

function stopCountdown() {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

onBeforeUnmount(() => {
  stopCountdown()
})

// 关闭倒计时
const turnOffCountdown = () => {
  showConfirmModal.value = false
  isCloseCountdown.value = false
  emit('eventBusBrother')
}
/** 倒计时完成 */
const showOver = ref(false)
const countdownClose = () => {
  showOver.value = false
  // emit('eventBusBrother')
}

// 确认下单模态窗相关
const showConfirmModal = ref(false)
const confirmCountdown = ref(58)
const confirmTimer = ref(null)
const confirmData = ref({
  direction: '漲',
  amount: '100 USD',
  huobiPrice: '119,365',
  kucoinPrice: '119,361.5',
  profit: '--'
})

function closeConfirmModal() {
  showConfirmModal.value = false
  if (timer.value) clearInterval(timer.value)
}
function handleContinueOrder() {
  closeConfirmModal()
}
function handleViewOrder() {
  closeConfirmModal()
  router.push('/quantContractOrder1')
}

// 简单确认弹窗
const showSimpleConfirm = ref(false)
function openSimpleConfirm() {
  showSimpleConfirm.value = true
}
function closeSimpleConfirm() {
  showSimpleConfirm.value = false
}

// 打字机动画相关
const typingSentences = [
  '取得買入交易',
  '正在分析最佳價格...',
  '請稍候，正在為您下單',
  'AI智能風控檢查中...',
  '訂單即將完成，請耐心等待'
]
const currentTyped = ref('') // 当前正在打的句子内容
const typingSentenceIdx = ref(0)
const typingCharIdx = ref(0)
const typingTimer = ref(null)

function startTyping() {
  currentTyped.value = ''
  typingSentenceIdx.value = 0
  typingCharIdx.value = 0
  if (typingTimer.value) clearTimeout(typingTimer.value)
  typeNextChar()
}
function typeNextChar() {
  const sentence = typingSentences[typingSentenceIdx.value]
  if (typingCharIdx.value < sentence.length) {
    currentTyped.value += sentence[typingCharIdx.value]
    typingCharIdx.value++
    typingTimer.value = setTimeout(typeNextChar, 150)
  } else {
    // 当前句打完，延迟后清空并打下一句
    setTimeout(() => {
      currentTyped.value = ''
      typingSentenceIdx.value++
      typingCharIdx.value = 0
      if (typingSentenceIdx.value < typingSentences.length) {
        typingTimer.value = setTimeout(typeNextChar, 300) // 句间延迟
      }
    }, 600)
  }
}

function handleOrder() {
  const val = Number(amount.value)
  if (!val || val < 100) {
    toastMsg.value = '最小交易额100'
    showToast.value = true
    setTimeout(() => showToast.value = false, 1500)
    return
  }
  showOrderProgress.value = true
  progress.value = 0
  startTyping()
  if (progressTimer.value) clearInterval(progressTimer.value)
  progressTimer.value = setInterval(() => {
    if (progress.value < 100) {
      progress.value += 0.55 // 约11~12秒完成
      if (progress.value > 100) progress.value = 100
    } else {
      clearInterval(progressTimer.value)
      // 这里可加订单完成逻辑
      determine()
    }
  }, 60)
}
function closeOrderProgress() {
  showOrderProgress.value = false
  if (progressTimer.value) clearInterval(progressTimer.value)
  if (typingTimer.value) clearTimeout(typingTimer.value)
}
function handleSimpleConfirm() {
  
  // handleOrder()
  determine()
  closeSimpleConfirm()
  
}



function handleOrderBtn() {
  const val = Number(amount.value)

  // ✅ 如果金额为空
  if (!val) {
    _toast(t('25_inputEmpty')) // 使用 t()，不会报 setup 错误
    return
  }

  // ✅ 如果金额小于 100
  if (val < 100) {
    _toast(t('25_inputMin'))
    return
  }

  // ✅ 正常打开确认弹窗
  openSimpleConfirm()
}


const selectedDirection = ref(1) // up 或 down
const selectDirection = (dir) => {
  selectedDirection.value = dir
}
</script>
<style lang="scss" scoped>
.placeholder {
  height: 104px;
}

.hightItem {
  color: #17ac74 !important;
}

.line {
  height: 5px;
  background: var(--ex-div-bgColor10);
}

.entrust {
  height: 50px;
  display: flex;
  padding: 0 15px;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--ex-border-color);

  .entrustL {
    font-size: 14px;
    color: var(--ex-default-font-color);
    display: flex;

    .entrustItem {
      margin-right: 16px;
    }
  }

  .entrustR {
    display: flex;
    align-items: center;

    .entrustRImg {
      width: 16px;
      height: 12px;
    }

    .entrustRUpdateImg {
      margin-left: 20px;
      width: 12px;
      height: 12px;
    }
  }
}

// 分享弹出层
.share-revenue-box {
  z-index: 99;

  .share-revenue {
    :deep(.share-commission) {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      background: var(--ex-default-background-color);
      min-width: 300px;
      border-radius: 30px;
    }
  }
}
.order-ui-box {
  background: #fff;
  border-radius: 10px;
  box-shadow: none;
  margin: 18px 0 0 0;
  padding: 10px 16px;
  width: 100%; 
  font-family: inherit;

}
.order-ui-label {
  font-size: 12px;
  color: #222;
  font-weight: 600;
  margin-bottom: 8px;
  margin-left: 2px;
}
.order-ui-row {
  display: flex;
  align-items: center;
  width: 100%;
}
.order-ui-row-top {
  gap: 10px;
  margin-bottom: 10px;
}
.order-ui-select-wrap {
  display: flex;
  align-items: center;
  border-radius: 8px;
  padding: 0 10px 0 8px;
  height: 40px;
  min-width: 110px;
  border: 1px solid #ececec;
  justify-content:space-around;
}
.order-ui-icon-time {
  width: 22px;
  height: 22px;
  margin-right: 4px;
}
.order-ui-select {
  border: none;
  background: transparent;
  font-size: 16px;
  color: #222;
  font-weight: 600;
  outline: none;
  min-width: 50px;
}
.order-ui-btn {
  height: 40px;
  min-width: 80px;
  border-radius: 8px;
  border: none;
  font-size: 12px;
  font-weight: 600;
  margin-left: 8px;
  background: #f6f7fa;
  color: #222;
  transition: background 0.2s, color 0.2s;
}
// 涨跌按钮选中样式
.order-ui-btn-up.active {
  background: #03b303;
  color: #fff;
}
.order-ui-btn-down.active {
  background: #f10430;
  color: #fff;
}
.order-ui-btn-down {
  background: #ececec;
  color: #888;
}
.order-ui-row-rate {
  margin: 10px 0 10px 0;
  width: 100%;
}
.order-ui-rate-box {
  width: 100%;
  background: #f6f7fa;
  border-radius: 8px;
  padding: 10px 0 10px 24px;
  font-size: 14px;
  font-weight: 600;
  color: #222;
  gap: 12px;
  text-align: center;
}
.order-ui-rate-label {
  color: #222;
  font-weight: 600;
  margin-right: 8px;
}
.order-ui-rate-value { 
  font-weight: 600;
}
.order-ui-row-bg {
  border-radius: 8px;
  flex-direction: column;
  gap: 0;
  margin-bottom: 0;
}
.order-ui-row-amount {
  justify-content: space-between;
  font-size: 15px;
  color: #222;
  margin-bottom: 10px;
}
.order-ui-amount-label {
  font-weight: 600;
}
.order-ui-amount-balance {
  color: #888;
  font-size: 13px;
}
.order-ui-row-input {
  justify-content: flex-start;
  gap: 10px;
}
.order-ui-currency {
  display: flex;
  align-items: center;
  border-radius: 8px;
  padding: 0 12px 0 8px;
  height: 38px;
  font-size: 16px;
  color: #000;
  font-weight: 600;
  border: 1px solid #ccc;
  gap: 4px;
}
.order-ui-icon-usd {
  width: 26px;
  height: 26px;
  margin-right: 2px;
}
.order-ui-input {
  border: 1px solid #ccc;
  background: #fff;
  border-radius: 8px;
  padding: 0 16px;
  font-size: 16px;
  width: 140px;
  height: 38px;
  color: #bbb;
  font-weight: 600;
  outline: none;
}
.order-ui-btn-all {
  background: #000;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 0 22px;
  font-size: 16px;
  height: 38px;
  font-weight: 600;
  margin-left: 8px;
  cursor: pointer;
}
.order-ui-row-profit {
  margin-top: 12px;
  font-size: 15px;
  color: #222;
  gap: 8px;
  margin-left: 2px;
}
.order-ui-profit-label {
  color: #888;
}
.order-ui-profit-value {
  color: #222;
  font-weight: 600;
}
.order-bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 14px 0 12px 0;
  display: flex;
  justify-content: center;
  z-index: 100;
}
.order-confirm-btn {
  width: 95%;
  max-width: 420px;
  height: 46px;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 28px;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 2px;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.08);
  transition: background 0.2s;
}
.order-confirm-btn:active {
  background: #222;
}
.time-popup-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.15);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
.time-popup-sheet {
  width: 100vw;
  max-width: 100vw;
  background: #fff;
  border-radius: 18px 18px 0 0;
  box-shadow: 0 -2px 16px 0 rgba(0,0,0,0.08);
  padding: 0 0 12px 0;
  position: relative;
  animation: popupUp 0.25s cubic-bezier(.4,0,.2,1);
}
@keyframes popupUp {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}
.time-popup-close {
  position: absolute;
  right: 18px;
  top: 14px;
  font-size: 22px;
  color: #bbb;
  cursor: pointer;
  z-index: 2;
}
.time-popup-list {
  padding-top: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.time-popup-item {
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: #222;
  padding: 16px 0;
  border-bottom: 1px solid #f2f2f2;
  cursor: pointer;
  background: #fff;
  transition: background 0.2s, color 0.2s;
}
.time-popup-item:last-child {
  border-bottom: none;
}
.time-popup-item.active {
  color: #17ac74;
  font-weight: 700;
  background: #f6f7fa;
}

.toast {
  position: fixed;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0,0,0,0.8);
  color: #fff;
  padding: 12px 28px;
  border-radius: 16px;
  font-size: 16px;
  z-index: 2000;
}
.order-progress-modal {
  position: fixed;
  left: 0; right: 0; bottom: 0; top: 0;
  background: rgba(0,0,0,0.25);
  z-index: 3000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
.order-progress-content {
  background: #fff;
  border-radius: 24px 24px 0 0;
  width: 100vw;
  max-width: 100vw;
  padding: 36px 24px 32px 24px;
  box-shadow: 0 -8px 32px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: slideUp 0.3s;
}
.order-progress-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 18px;
}
.order-progress-title {
  font-size: 18px;
  font-weight: 700;
  margin-bottom: 12px;
  color: #222;
}
.order-progress-desc {
  font-size: 16px;
  color: #222;
  margin-bottom: 24px;
  min-height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  transition: min-height 0.2s;
}
.order-progress-bar-wrap {
  width: 90%;
  margin: 0 auto;
  position: relative;
}
.order-progress-bar-bg {
  width: 100%;
  height: 12px;
  background: #eee;
  border-radius: 8px;
  overflow: hidden;
}
.order-progress-bar {
  height: 12px;
  background: linear-gradient(90deg, #2e7cff 0%, #4bb3ff 100%);
  border-radius: 8px;
  transition: width 0.2s;
}
.order-progress-percent {
  position: absolute;
  top: 18px;
  font-size: 14px;
  color: #fff;
  background: #2e7cff;
  border-radius: 8px;
  padding: 2px 10px;
  left: 0;
  min-width: 60px;
  text-align: center;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(46,124,255,0.08);
  transition: left 0.2s;
}
.confirm-modal-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 4000;
  display: flex;
  align-items: center;
  justify-content: center;
}
.confirm-modal {
  background: #fff;
  border-radius: 18px;
  width: 340px;
  max-width: 90vw;
  padding: 24px 20px 20px 20px;
  box-shadow: 0 4px 32px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.confirm-modal-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  margin-bottom: 18px;
  margin-top: 0px;
  border-bottom: 1px solid lightgray;
}
.confirm-modal-close {
  font-size: 18px;
  color: #888;
  cursor: pointer;
  font-weight: 400;
  transition: color 0.2s;
}
.confirm-modal-close:hover {
  color: #222;
}
.confirm-modal-timer {
  display: flex;
  gap: 8px;
  margin-bottom: 18px;
}
.timer-box {
  width: 44px;
  height: 44px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-family: 'Courier New', Courier, monospace;
  font-weight: 700;
  color: #fff;
}
.timer-box.red { background: #ff5a5a; }
.timer-box.green { background: #1ecb81; }
.timer-box.yellow { background: #ffc24b; color: #222; }

.confirm-modal-info {
  width: 100%;
  margin-bottom: 18px;
}
.confirm-modal-info .row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 15px;
}
.confirm-modal-info .label {
  color: #999;
  font-weight: 500;
}
.confirm-modal-info .value {
  color: #222;
  font-weight: 600;
}
.confirm-modal-info .value.green {
  color: #1ecb81;
}
.confirm-modal-info .value.red { color: #ff5a5a; }
.profit-bar {
  display: inline-block;
  width: 18px;
  height: 8px;
  background: repeating-linear-gradient(90deg, #eee 0 4px, #ccc 4px 8px);
  border-radius: 4px;
  margin-left: 6px;
  vertical-align: middle;
}
.confirm-modal-btns {
  width: 100%;
  display: flex;
  gap: 16px;
  margin-top: 10px;
}
.view-btn, .continue-btn {
  flex: 1;
  padding: 10px 0;
  border-radius: 24px;
  border: none;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.view-btn {
  background: #f5f5f5;
  color: #222;
}
.continue-btn {
  background: #1ecb81;
  color: #fff;
}
.continue-btn:active {
  background: #17b06b;
}
.simple-confirm-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 4100;
  display: flex;
  align-items: center;
  justify-content: center;
}
.simple-confirm-modal {
  background: #fff;
  border-radius: 16px ;
  width: 320px;
  max-width: 90vw;
  padding: 28px 0 0 0;
  box-shadow: 0 4px 32px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.simple-confirm-title {
  font-size: 18px;
  font-weight: 700;
  color: #444;
  text-align: center;
  margin-bottom: 18px;
}
.simple-confirm-btns {
  display: flex;
  width: 100%;
  border-top: 1px solid #eee;
}
.simple-cancel, .simple-ok {
  flex: 1;
  padding: 14px 0;
  border: none;
  background: none;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  color: #444;
  transition: color 0.2s;
}
.simple-cancel {
  border-right: 1px solid #eee;
}
.simple-ok {
  color: #2e7cff;
}
.simple-ok:active {
  color: #1a5bb8;
}

// .circle-container {
//   position: relative;
//   display: inline-block;
// }

.circle-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-weight: bold;
  font-size: 16px;
  color: #333;
  pointer-events: none; /* 防止遮挡点击 */
}
</style>
